import request from "@/axios/request";
const { ElMessage } = require("element-plus");

export default {
  name: "TenantRecord",
  data() {
          return {
              loading: true,
              tenantId: null,
              username: "",
              password: "",
              phone: "",
              email: "",
              currentPage: 1,
              pageSize: 10,
              total: 0,
              tenant_total: 0,
              transaction_total: 0,
              allTransactionData: [],
              tableTransactionData: [],
              allLandlordData: [],
              tableLandlordData: [],
              allData: [],       // 存储全量数据
              tableData: [],     // 当前页数据
              // allData: [{
              //     houseId: 1,
              //     title: "学院十一峯",
              //     description: "学院十一峯位于温州市鹿城区滨江街道会展路与学院路交汇处，由金地集团与新希望地产联合开发，2021年竣工交付。项目总户数1276户，包含11栋板塔结合建筑，绿化率30%，容积率3.13，物业费4.7元/㎡·月（含能耗费）。小区定位改善型住宅，主力户型为143-189㎡的四居室，南北通透设计，精装修交付。‌‌",
              //     price: "5000",
              //     address: "温州市鹿城区滨江街道会展路与学院路交汇处",
              //     area: "浙江省",
              //     size: 140,
              //     rooms: 3,
              //     floor: 3,
              //     landlordId: 1,
              //     status: "待审核",
              //     imageUrl: "https://img2.baidu.com/it/u=668963934,1194070255&fm=253&fmt=auto&app=138&f=JPEG?w=661&h=500"
              // }]
          };
      },
      computed: {
          paginatedData() {
              const start = (this.currentPage - 1) * this.pageSize;
              const end = start + this.pageSize;
              return this.allData.slice(start, end);
          },
          paginatedLandlordData() {
              const start = (this.currentPage - 1) * this.pageSize;
              const end = start + this.pageSize;
              return this.allLandlordData.slice(start, end);
          },
          paginatedTransactionData() {
              const start = (this.currentPage - 1) * this.pageSize;
              const end = start + this.pageSize;
              return this.allTransactionData.slice(start, end);
          }
      },
      created() {
          this.loadMyInfo();
          this.load();
          this.loading = true;
          setTimeout(() => {
              this.loading = false;
          }, 1000);
      },
      methods: {
          async load() {
              try{
                  // 获取所有房屋信息
                  const res = await request.get("/house/findAll");
                  if (res.code === 200) {
                      this.allData = res.data || [];
                      this.total = this.allData.length;
                      this.tableData = this.paginatedData;
                  } else {
                      ElMessage.error(res.msg || "加载失败");
                      this.allData = [];
                      this.tableData = [];
                      this.total = 0;
                  }
                  // 获取所有租户信息
                  const res_landlord = await request.get("/landlord/findAll");
                  if (res_landlord.code === 200) {
                      this.allLandlordData = res_landlord.data || [];
                      this.landlord_total = this.allLandlordData.length;
                      this.tableLandlordData = this.paginatedLandlordData;
                  } else {
                      ElMessage.error(res_landlord.msg || "加载失败");
                      this.allLandlordData = [];
                      this.tableLandlordData = [];
                      this.landlord_total = 0;
                  }
                  const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
                  this.tenantId = token.tenantId;
                  // 获取所有交易信息
                  const res_transaction = await request.get(`/record/tenant/${this.tenantId}`);
                  if (res_transaction.code === 200) {
                      this.allTransactionData = res_transaction.data || [];
                      this.transaction_total = this.allTransactionData.length;
                      this.tableTransactionData = this.paginatedTransactionData;
                  } else {
                      ElMessage.error(res_transaction.msg || "加载失败");
                      this.allTransactionData = [];
                      this.tableTransactionData = [];
                      this.transaction_total = 0;
                  }
                  console.log(this.allTransactionData);
                  this.loading = false;
              } catch (err){
                  console.error(err);
                  ElMessage.error("网络错误，请稍后再试");
  
                  this.allData = [];
                  this.tableData = [];
                  this.total = 0; 
  
                  this.allTenentData = [];
                  this.tableLandlordData = [];
                  this.tenant_total = 0;
  
                  this.allTransactionData = [];
                  this.tableTransactionData = [];
                  this.transaction_total = 0;
  
                  this.loading = false;
              }
          },
          loadMyInfo() {
              const token = JSON.parse(window.sessionStorage.getItem('userInfo'));
  
              if(!token) {
                  ElMessage.error("获取用户信息失败");
                  console.log("获取用户信息失败");
                  return;
              }
  
              this.tenantId = token.tenantId;
              this.username = token.username;
              this.password = token.password;
              this.phone = token.phone;
              this.email = token.email;
          },
          SignOut() {
              sessionStorage.clear()
              ElMessage({
                  message: '用户退出登录',
                  type: 'success',
              });
              this.$router.replace({path: '/Login'});
          },
          handleSizeChange(pageSize) {
              this.pageSize = pageSize;
              this.tableData = this.paginatedData;
          },
          handleCurrentChange(pageNum) {
              this.currentPage = pageNum;
              this.tableData = this.paginatedData;
          },
          getTitle(houseId) {
              const house = this.allData.find(item => item.houseId === houseId);
              if (house.title === ""){
                  return "未知名称";
              }
              return house.title;
          },
          getLandlordId(houseId) {
            const house = this.allData.find(item => item.houseId === houseId);
            const landlordId = house.landlordId;
            return landlordId;
          },
          getLandlordUsername(houseId) {
            const house = this.allData.find(item => item.houseId === houseId);
            const landlordId = house.landlordId;
            const landlord = this.allLandlordData.find(item => item.landlordId === landlordId);
            
            if (!landlord){
              return "未知用户";
            }
            return landlord.username;
          },
          getLandlordPhone(houseId) {
            const house = this.allData.find(item => item.houseId === houseId);
            const landlordId = house.landlordId;
              const landlord = this.allLandlordData.find(item => item.landlordId === landlordId);
              if (!landlord){
                  return "未知电话号码";
              }
              return landlord.phone;
          },
          getLandlordEmail(houseId) {
            const house = this.allData.find(item => item.houseId === houseId);
            const landlordId = house.landlordId;
              const landlord = this.allLandlordData.find(item => item.landlordId === landlordId);
              if (!landlord){
                  return "未知邮箱";
              }
              return landlord.email;
          },
              //时间显示
          formatTime(isoTime) {
            if (!isoTime) return "-";
            const date = new Date(isoTime);
            // 手动格式化避免浏览器差异
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hour = String(date.getHours()).padStart(2, '0');
            const minute = String(date.getMinutes()).padStart(2, '0');
            const second = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
          },
      },
  };